import { useState, useEffect } from 'react'
import Sidebar from './components/Sidebar'
import HookDetail from './components/HookDetail'
import InterviewDetail from './components/InterviewDetail'
import { HookItem, InterviewItem } from './types'
import { getHookRoutes, getInterviewRoutes, getRouteById } from './routes'
import { loadHookContent, loadInterviewContent } from './utils/contentLoader'

function App() {
  const [selectedHook, setSelectedHook] = useState<HookItem | null>(null)
  const [selectedInterview, setSelectedInterview] = useState<InterviewItem | null>(null)
  const [sidebarOpen, setSidebarOpen] = useState(true)

  // 初始化时加载第一个Hook
  useEffect(() => {
    const loadInitialContent = async () => {
      const firstHookRoute = getHookRoutes()[0]
      if (firstHookRoute) {
        const hookContent = await loadHookContent(firstHookRoute)
        setSelectedHook(hookContent)
      }
    }

    loadInitialContent()
  }, [])

  const handleSelectHook = async (routeId: string) => {
    try {
      const route = getRouteById(routeId)
      if (route && route.type === 'hook') {
        const hookContent = await loadHookContent(route)
        setSelectedHook(hookContent)
        setSelectedInterview(null)
      }
    } catch (error) {
      console.error('加载Hook内容失败:', error)
    }
  }

  const handleSelectInterview = async (routeId: string) => {
    try {
      const route = getRouteById(routeId)
      if (route && route.type === 'interview') {
        const interviewContent = await loadInterviewContent(route)
        setSelectedInterview(interviewContent)
        setSelectedHook(null)
      }
    } catch (error) {
      console.error('加载面试题内容失败:', error)
    }
  }

  const hookRoutes = getHookRoutes()
  const interviewRoutes = getInterviewRoutes()

  return (
    <div className="h-screen flex bg-gray-50">
      <Sidebar
        hooks={hookRoutes}
        interviews={interviewRoutes}
        selectedHook={selectedHook}
        onSelectHook={handleSelectHook}
        onSelectInterview={handleSelectInterview}
        isOpen={sidebarOpen}
        onToggle={() => setSidebarOpen(!sidebarOpen)}
      />

      <main className={`flex-1 overflow-y-auto transition-all duration-300`}>
        {selectedHook ? (
          <div className="p-4">
            <HookDetail hook={selectedHook} />
          </div>
        ) : selectedInterview ? (
          <div className="p-4">
            <InterviewDetail interview={selectedInterview} />
          </div>
        ) : (
          <div className="p-6 text-center text-gray-500">
            请选择一个Hook或面试题查看详情
          </div>
        )}
      </main>
    </div>
  )
}

export default App 